#-*- coding:utf-8 -*-*

from django.shortcuts import get_object_or_404
from django.utils import simplejson
from confs import SmartConf

g_smart_conf = {}


def encode(validates):
    d = {}
    for k, v in validates.items():
        if k not in ('title', 'content'):
            d[k] = v["value"]

    return simplejson.dumps(d)


def decode(s):
    return simplejson.loads(s)


def getconf(typeid):
    ret = g_smart_conf.get(typeid, None)
    if ret: return ret

    conf = SmartConf[typeid]

    #对radio, select的值域进行预处理
    for f in conf["fields"]:
        if f["type"] == "radio":
            f["value_range"] = [x["value"] for x in f["choices"]]
        if f["type"] == "select":
            f["value_range"] = [x["value"] for x in f["selects"]]

    g_smart_conf[typeid] = conf

    return conf


def validate(postdatas, conf):
    result = True
    data = {} 

    fields = conf["fields"]
    for f in fields:
        _f = {}
        n = f["name"]
        t = f["type"]
        v = postdatas.get(n, "")
        _f["value"] = v

        if len(v) == 0:
            result = False
            _f["error"] = "请输入[%s]"%(f["tag"])
            data[n] = _f
            continue
        
        if t == 'uint':
            if  v.isdigit() and int(v) > 0:
                _f["value"] = int(v)
            else:
                result = False
                _f["error"] = "请输入一个数值"

        if t in ('string', 'text'):
            if len(v) > 0 and len(v) < f["maxlen"]:
                _f["value"] = v
            else:
                result = False
                _f["error"] = "内容长度错误"  

        if t in ('radio', 'select'):
            if not v.isdigit():
                result = False
                _f["error"] = "非法的数据"  
            elif int(v) not in f["value_range"]:
                result = False
                _f["error"] = "不合理的数据"  
            else:
                _f["value"] = int(v) 


        data[n] = _f

    return result, data        

